# frozen_string_literal: true

require 'spec_helper'
# rubocop:disable Layout/LineLength
RSpec.describe Gitlab::BackgroundMigration::TruncateOverlongVulnerabilityHtmlTitles, schema: 20221110100602, feature_category: :vulnerability_management do
  # rubocop:enable Layout/LineLength

  let(:namespaces) { table(:namespaces) }
  let(:projects) { table(:projects) }
  let(:vulnerabilities) { table(:vulnerabilities) }
  let(:users) { table(:users) }
  let(:namespace) { namespaces.create!(name: 'name', path: 'path') }

  let(:project) do
    projects
      .create!(name: "project", path: "project", namespace_id: namespace.id, project_namespace_id: namespace.id)
  end

  let!(:user) { create_user! }

  let!(:vulnerability_1) { create_vulnerability!(title_html: 'a' * 900, project_id: project.id, author_id: user.id) }
  let!(:vulnerability_2) { create_vulnerability!(title_html: 'a' * 801, project_id: project.id, author_id: user.id) }
  let!(:vulnerability_3) { create_vulnerability!(title_html: 'a' * 800, project_id: project.id, author_id: user.id) }
  let!(:vulnerability_4) { create_vulnerability!(title_html: 'a' * 544, project_id: project.id, author_id: user.id) }

  subject do
    described_class.new(
      start_id: vulnerabilities.minimum(:id),
      end_id: vulnerabilities.maximum(:id),
      batch_table: :vulnerabilities,
      batch_column: :id,
      sub_batch_size: 200,
      pause_ms: 2.minutes,
      connection: ApplicationRecord.connection
    )
  end

  describe '#perform' do
    it 'truncates the vulnerability html title when longer than 800 characters' do
      subject.perform

      expect(vulnerability_1.reload.title_html.length).to eq(800)
      expect(vulnerability_2.reload.title_html.length).to eq(800)
      expect(vulnerability_3.reload.title_html.length).to eq(800)
      expect(vulnerability_4.reload.title_html.length).to eq(544)
    end
  end

  private

  # rubocop:disable Metrics/ParameterLists
  def create_vulnerability!(
    project_id:, author_id:, title: 'test', title_html: 'test', severity: 7, confidence: 7, report_type: 0, state: 1,
    dismissed_at: nil
  )
    vulnerabilities.create!(
      project_id: project_id,
      author_id: author_id,
      title: title,
      title_html: title_html,
      severity: severity,
      confidence: confidence,
      report_type: report_type,
      state: state,
      dismissed_at: dismissed_at
    )
  end
  # rubocop:enable Metrics/ParameterLists

  def create_user!(name: "Example User", email: "user@example.com", user_type: nil)
    users.create!(
      name: name,
      email: email,
      username: name,
      projects_limit: 10
    )
  end
end
